//
//  RequestManager.m
//  GreatMaster
//
//  Created by   on 2017/1/16.
//  Copyright © 2020年 . All rights reserved.
//

#import "RequestManager.h"
#import "AFNetworking.h"

#define kSafeString(str) [str isKindOfClass:[NSString class]] > 0 ? str : @""

@interface RequestManager ()

@property (nonatomic) AFHTTPSessionManager *sessionManager;
@property (nonatomic) AFHTTPSessionManager *versionSessionManager;//版本
@property (nonatomic) AFHTTPSessionManager *translateSessionManager;//翻译

@end

@implementation RequestManager

+ (instancetype)sharedInstance {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        
    });
    return instance;
}

#pragma mark - 配置请求底层参数

//打点
- (AFHTTPSessionManager *)sessionManager {
    if (!_sessionManager) {
        //主Url 可以封装起来统一管理,也可以直接写在GET参数里单独管理
        NSURL *baseUrl = [NSURL URLWithString:kManagementBaseUrl];
        //AFHTTPSessionManager 创建一个网络请求
        _sessionManager = [[AFHTTPSessionManager manager] initWithBaseURL:baseUrl];
        _sessionManager.securityPolicy.allowInvalidCertificates = YES;
        _sessionManager.securityPolicy.validatesDomainName = NO;
        //Requests 请求Header参数
        _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [_sessionManager.requestSerializer setValue:@"multipart/form-data; boundary=FormBoundary" forHTTPHeaderField:@"Content-Type"];
        _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    }
    return _sessionManager;
}



//打点
- (void)saveRequeseWithKey:(SaveRequestType)type{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *time = [formatter stringFromDate:[NSDate date]];
    
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    if (type == SaveRequestTypeSellpage) {
        [params setValue:@"sellpage" forKey:@"key"];
    } else if (type == SaveRequestTypeBuy_success) {
        [params setValue:@"buy_success" forKey:@"key"];
    } else if (type == SaveRequestTypeOpen) {
        [params setValue:@"open" forKey:@"key"];
    }else if (type == SaveRequestTypeClick) {
        [params setValue:@"click" forKey:@"key"];
    }
    
    [params setValue:ksub_type forKey:@"sub_type"];//Likappt,sellpage，buy_success
    [params setValue:kSafeString(@"") forKey:@"ip"];
    [params setValue:kSafeString(time) forKey:@"event_time"];
    [params setValue:@"/" forKey:@"uid"];
    [params setValue:@"/" forKey:@"remark"];

    [params setValue:localVersion forKey:@"version"];
    
    [self.sessionManager POST:@"" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [params.allKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
            [formData appendPartWithFormData:data name:key];
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"markPointSuccess--------%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSInteger code = [dic[@"code"] integerValue];
            NSString *message = dic[@"message"];
            id data = dic[@"data"];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error--------%@",error.description);
    }];
}
- (void)saveRequestWithKey:(NSString *)key sub_type:(NSString *)sub_type success:(void (^)(id responseObject))success failure:(void (^)(NSString *errorMsg))failure {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *time = [formatter stringFromDate:[NSDate date]];
    
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];

    [params setValue:kSafeString(key) forKey:@"key"];
    [params setValue:ksub_type forKey:@"sub_type"];//Likappt,sellpage，buy_success
    [params setValue:kSafeString(@"") forKey:@"ip"];
    [params setValue:kSafeString(time) forKey:@"event_time"];
    [params setValue:@"/" forKey:@"uid"];
    [params setValue:@"/" forKey:@"remark"];

    [params setValue:localVersion forKey:@"version"];
    
    [self.sessionManager POST:@"" parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [params.allKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
            [formData appendPartWithFormData:data name:key];
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"--------%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSInteger code = [dic[@"code"] integerValue];
            NSString *message = dic[@"message"];
            id data = dic[@"data"];
            if (code == 200) {
                success(data);
            } else {
                if (failure) {
                    failure(message);
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.domain);
        }
    }];
}

#pragma mark - 各种请求

//GET
- (void)getRequestWithUrl:(NSString *)url params:(id)params success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *message))failure {

    [self.sessionManager GET:url parameters:params headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSInteger code = [dic[@"code"] integerValue];
                NSString *message = dic[@"msg"];
                id data = dic[@"data"];
                if (code == 200) {
                    success(data);
                } else {
                    if (failure) {
                        failure(message);
                    }
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.domain);
        }
    }];
}

//POST
- (void)postRequestWithUrl:(NSString *)url params:(id)params success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *message))failure {
    
    
    [self.sessionManager POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSInteger code = 1;
                NSString *message = dic[@"msg"];
                id data = dic[@"data"];
                if (code == 1) {
                    NSLog(@"responseObject data ==== %@",data);
                    success(data);
                } else {
                    if (failure) {
                        failure(message);
                    }
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.domain);
        }
    }];
}

//PUT
- (void)putRequestWithUrl:(NSString *)url params:(id)params success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *message))failure {
    
    [self.sessionManager PUT:url parameters:params headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSInteger code = [dic[@"code"] integerValue];
                NSString *message = dic[@"msg"];
                id data = dic[@"data"];
                if (code == 1) {
                    success(data);
                } else {
                    if (failure) {
                        failure(message);
                    }
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.domain);
        }
    }];
}

//PATCH
- (void)patchRequestWithUrl:(NSString *)url params:(id)params success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *message))failure {

    
    [self.sessionManager PATCH:url parameters:params headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSInteger code = [dic[@"code"] integerValue];
                NSString *message = dic[@"msg"];
                id data = dic[@"data"];
                if (code == 1) {
                    success(data);
                } else {
                    if (failure) {
                        failure(message);
                    }
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.domain);
        }
    }];
}

//DELETE
- (void)deleteRequestWithUrl:(NSString *)url params:(id)params success:(void (^)(id  _Nullable responseObject))success failure:(void (^)(NSString *message))failure {

    [self.sessionManager DELETE:url parameters:params headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = (NSDictionary *)responseObject;
                NSInteger code = [dic[@"code"] integerValue];
                NSString *message = dic[@"msg"];
                id data = dic[@"data"];
                if (code == 1) {
                    success(data);
                } else {
                    if (failure) {
                        failure(message);
                    }
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.domain);
        }
    }];
}

@end
